package com.example.newsmanager.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {
    private static final String secret="my_framework";
    public static String createJwt(String key){
        Map<String,Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withHeader(header).withClaim("infoCode",key).sign(Algorithm.HMAC256(secret));
        log.info("create token:{}",token);
        return token;
    }

    public static String parseJwt(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        DecodedJWT decodedJWT = verifier.verify(token);
        String infoCode = decodedJWT.getClaim("infoCode").asString();
        log.info("parse token:{}",infoCode);
        return infoCode;
    }
}
